package com.hezhiqin.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: hezhiqin
 * @time: 2020/7/15 10:14
 */

@Component
public class MqttUtils {

    public static final ConcurrentHashMap<String,Object> concurrentHashMap  = new ConcurrentHashMap<String,Object> ();

    @PreDestroy
    public static void clear(){
        System.out.println("-------------------清空内存------------------------");

        concurrentHashMap.clear();
    }



    public static String deleteMqttClient(String key){
        if (concurrentHashMap.containsKey(key)){
            MqttClient mqttClient = (MqttClient) MqttUtils.concurrentHashMap.get(key);

            try {
                mqttClient.disconnect();

            } catch (MqttException e) {
                e.printStackTrace();
            }finally {
                concurrentHashMap.remove(key);
            }
            return "删除["+key+"]成功";
        }else {
            return key+"不存在，删除["+key+"]失败";
        }


    }

    public static String addMqttClient(NasInfo info) {
        if (!MqttUtils.concurrentHashMap.containsKey(info.getClientId())){
            DynamicMqttClient dynamicMqttClient = new DynamicMqttClient(info.getUsername(),info.getPassword(),info.getHostUrl(),info.getClientId(),info.getDefaultTopic(),info.getCompletionTimeout());
            dynamicMqttClient.connection();
            MqttClient mqttClient = dynamicMqttClient.getMqttClient();
            MqttUtils.concurrentHashMap.put(info.getClientId(),mqttClient);
            return "添加["+info.getClientId()+"]成功";
        }else {
            return info.getClientId()+ "已连接,添加["+info.getClientId()+"]失败";
        }

    }
}
